#!/usr/bin/env python
# -*- coding:utf-8 -*-

import json

import os
import time

from scpy.logger import get_logger
from crawler.qichacha_crawler import QichachaCrawler
import utils

logger = get_logger(__file__)

PROVINCES = {
    u"安徽": "AH",
    u"北京": "BJ",
    u"重庆": "CQ",
    u"福建": "FJ",
    u"甘肃": "GS",
    u"广东": "GD",
    u"广西": "GX",
    u"贵州": "GZ",
    u"海南": "HAIN",
    u"河北": "HB",
    u"黑龙江": "HLJ",
    u"河南": "HEN",
    u"湖北": "HUB",
    u"湖南": "HUN",
    u"江苏": "JS",
    u"江西": "JX",
    u"吉林": "JL",
    u"辽宁": "LN",
    u"内蒙古": "NMG",
    u"宁夏": "NX",
    u"青海": "QH",
    u"山东": "SD",
    u"上海": "SH",
    u"山西": "SX",
    u"陕西": "SAX",
    u"四川": "SC",
    u"天津": "TJ",
    u"新疆": "XJ",
    u"西藏": "XZ",
    u"云南": "YN",
    u"浙江": "ZJ"
}


def query_db(filter):
    result = utils.query_from_db('cacheQichacha', filter)
    if result:
        del result['_id']
        del result['updateTime']
        return result
    return None


def is_valuable_result(data, province):
    if not data:
        return False
    if data['province'] == province:
        return True
    if not province:
        return True
    return False


def search(key, province='', forced_latest=False, strictMode=False):
    if province and province in PROVINCES:
        province = PROVINCES[province]
    if not forced_latest:
        result = query_db({'key': key})
        if is_valuable_result(result, province):
            if not strictMode:
                return result
            if result['companyName'] == key:
                return result
        result = query_db({'companyName': key})
        if is_valuable_result(result, province):
            if not strictMode:
                return result
            if result['companyName'] == key:
                return result
    crawler = QichachaCrawler(key, QichachaCrawler.TYPE_COMPANY, province)
    result = crawler.run(QichachaCrawler.MODE_SINGLE, forced_latest, strictMode)
    if isinstance(result, dict) and result:
        result['key'] = key
        result['province'] = province
        utils.insert_into_db('cacheQichacha', {'key': key}, result)
        del result['_id']
        del result['updateTime']
        return result
    return False


def search_name(key, province=''):
    province = unicode(province)
    key = key.replace(u'(', u'（').replace(u')', u'）')
    if province and province in PROVINCES:
        province = PROVINCES[province]
    crawler = QichachaCrawler(key, QichachaCrawler.TYPE_COMPANY, province)
    result = crawler.check_name()
    if isinstance(result, list) and result:
        for l in result:
            try:
                utils.DB['companyNames'].insert({'_id': l['companyName']})
            except Exception, e:
                pass
        return result
    return False


if __name__ == '__main__':
    pass